<template>
  <div style="height:100%;width:100%;position:relative;">
      <div class="pagetop">
          <div style="width:100%;">
              <div style="width:100%;float:left">
                  <table style="font-size:12px;" class="table1style" border="0">
                      <tr>
                          <td>报告单元</td>
                          <td>
                              <rm-ddl-rptunit prgno="LIS321" v-model="txtrptunit" filterable :clearable="false" @change="handlerrptitemchange($event)" defaultflag="1" :appendtobody="true" visible-change:true width="200px;" @keyup.enter.native="inputautofocus($event, 'popinput1')" ref="popinput1"></rm-ddl-rptunit>
                          </td>
                          <td>标本日期</td>
                          <td>
                              <el-date-picker v-model="sampledatetime" type="date" placeholder="选择日期" style="width:100%" value-format="yyyy-MM-dd">
                              </el-date-picker>
                          </td>
                          <td align="right">样本号</td>
                          <td>
                              <el-input v-model="sampleno" placeholder="请输入样本号" style="width:100%" @keyup.enter.native="inputautofocus($event, 'popinput3')" ref="popinput3"></el-input>
                          </td>
                          <td></td>
                      </tr>
                      <tr>
                          <td>调整项目</td>
                          <td>
                              <el-input v-model="rpt_itemname" placeholder="双击选择调整项目" @dblclick.native="OpenRptitem"></el-input>
                          </td>
                          <td>调整公式</td>
                          <td>
                              <el-input v-model="justifyfun" placeholder="输入调整公式" style="width:100%" @keyup.enter.native="inputautofocus($event, 'popinput4')" ref="popinput4"></el-input>
                          </td>
                          <td style="text-align:center" colspan="3">
                              <p style="color:blue">
                                  注：请输入包含R（检验结果）的表达式，如：R*1.1为结果调整为原来的1.1倍
                              </p>
                          </td>
                      </tr>
                      <tr>
                          <td>仪器</td>
                          <td>
                              <el-select placeholder="请选择仪器" style="width:100%" clearable v-model="instrument">
                                  <el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in InstrumentList"></el-option>
                              </el-select>
                          </td>
                          <td>
                              <el-select v-if="ResultList&&ResultList.length>0" placeholder="请选择结果" style="width:80px;" v-model="resultnum" clearable>
                                  <el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in ResultList"></el-option>
                              </el-select>
                          </td>
                          <td>
                              <el-input v-if="ResultList&&ResultList.length>0" v-model="resulttxt" placeholder="输入结果内容" style="width:100%" ref="popinput4"></el-input>
                          </td>
                          <td>
                              <el-checkbox v-if="ResultList&&ResultList.length>0" v-model="checked">模糊</el-checkbox>
                          </td>
                      </tr>
                  </table>
              </div>
              <div style="width:100%;float:left">
                  <table class="table2style" style="float:right">
                      <tr>
                          <td>
                              <p :style="{color:saveRsColor}" style="text-align:center">{{saveRsText}}</p>
                          </td>
                          <td>
                              <el-button icon="el-icon-search" @click="btnRead()" type="primary">查询</el-button>
                          </td>
                          <td>
                              <el-button icon="el-icon-edit-outline" @click="btnJustify()">调整</el-button>
                          </td>
                          <td>
                              <el-button icon="el-icon-document" @click="saverecord()">保存</el-button>
                          </td>
                          <td>
                              <el-button icon="el-icon-delete" @click="btnDel()">删除</el-button>
                          </td>
                          <td>
                              <el-button icon="el-icon-s-release" @click="btnDelAll()">删除全部</el-button>
                          </td>
                      </tr>
                  </table>
              </div>
          </div>
      </div>
      <div class="pagecenter">
          <div class="middle-center">
              <div style="width:100%;height:93%;float:left;bottom:30px;position:absolute">
                  <vxe-table :loading="loading" :data.sync="tableData" border fit :mouse-config="{ selected: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, showIcon: false }" height="auto" header-align="center" highlight-current-row highlight-hover-row ref="xTable" resizable show-header-overflow="tooltip" show-overflow="tooltip" size="mini" stripe :cell-class-name="cellClassName" @current-change="currentChangeEvent"   @cell-dblclick="opendialog">
                      <vxe-table-column type="index" title="NO." width="50" align="center"></vxe-table-column>
                      <vxe-table-column field="sampleno" title="样本号" width="200"></vxe-table-column>
                      <vxe-table-column field="result_str" title="原始结果" width="200">
                          <template v-slot="{ row }">
                              <div :style="ResultClass(row)">
                                  <span>{{row.result_str}}</span>
                              </div>
                          </template>
                      </vxe-table-column>
                      <vxe-table-column field="justifyresult" title="调整后结果(双击开窗)" width="200" :edit-render="{ name: 'input', autoselect: true }">
                          <template v-slot="{ row }">
                              <div :style="ResultClass(row)">
                                  <span>{{row.justifyresult}}</span>
                              </div>
                          </template>
                          <template v-slot:edit="{row,rowIndex,column}">
                              <el-input v-model="row.justifyresult" @keyup.down.native="inputMove(1, column, rowIndex)" @keyup.up.native="inputMove(0, column, rowIndex)" @keyup.enter.native="enterMethod(row, rowIndex, column)"></el-input>
                          </template>
                      </vxe-table-column>
                      <vxe-table-column field="exeresult" title="处理结果" width="300">
                          <template v-slot:edit="{ row }">
                              <el-input v-model="row.exeresult"></el-input>
                          </template>
                      </vxe-table-column>
                  </vxe-table>
              </div>
              <div style="width:100%;height:30px;float:left;border:1px solid #CCC;border-top:none;bottom:0px;position:absolute">
                  <table class="table1style" style="color:blue">
                      <tr>
                          <td>共{{ datacnt }}笔</td>
                          <td width="40px"></td>
                          <td>均值：{{ dataavg }}</td>
                      </tr>
                  </table>
              </div>
          </div>
      </div>

      <el-dialog width="1000px" top="10px" :append-to-body="true" :close-on-click-modal="false" title="选择报告项目" :visible.sync="outerVisible" :destroy-on-close="true" v-if="diagx">
          <rm-pop-rptitem prgno="LIS321" @cancel="
        outerVisible = false;
        diagx = false;
      " :isAllRpt="1" @selitem="addrptitem" :rptunitid="txtrptunit" :currptitem="rpt_itemcode"></rm-pop-rptitem>
      </el-dialog>

      <el-dialog width="1000px" top="10px" :append-to-body="true" :close-on-click-modal="false" title="项目文字结果" :visible.sync="outerVisible2">
          <rm_ItemTxtResult @change="itemtxtresChage" :rpt_itemcode="rpt_itemcode" resultkind="0" @cancel="outerVisible2 = false"></rm_ItemTxtResult>
      </el-dialog>
  </div>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils";
export default {
  name: "LIS321",
  data() {
      return {
          txtrptunit: "",
          rpt_itemcode: "",
          rpt_itemname: "",
          instrument: "",
          sampledatetime: this.$pub.InitDate(),
          justifyfun: "",
          sampleno: "",
          resultnum: "",
          resulttxt: "",
          userno: "LIS",
          checked: false,
          islogin: false,
          loading: false,
          diagx: false,
          outerVisible: false,
          outerVisible2: false,
          okFirstLoading: true,
          tableData: [],
          selectrow: [],
          InstrumentList: [],
          ResultList: [],
          datacnt: 0,
          dataavg: 0,
          Options: {},//选项
          resultchangestyle: "",
          saveRsText:"",
          saveRsColor:"blue",
          saveSuccessCount:"",
          saveErrorCount:"",
      };
  },
  created() {
      //this.InitPageDate(); //初始化主列表
      this.InitOption();
  },
  mounted() {},
  updated() {
      if (this.okFirstLoading) {
          let currentrow = this.$refs.xTable.getData(0);
          this.$nextTick(() => {
              if (currentrow) {
                  this.okFirstLoading = false;
                  this.$refs.xTable.setCurrentRow(currentrow);
              }
          });
      }
  },
  methods: {
      handlerrptitemchange(rptunitid) {
          this.$nextTick(() => {
              this.txtrptunit = rptunitid;
          });
          this.instrument = "";
          this.getInstrumentList(rptunitid);
      },
      getInstrumentList(rptunitid) {
          this.$tool
              .request({
                  url: "LIS/LIS3/LIS321",
                  method: "post",
                  data: {
                      action: "getInstrumentList",
                      rptunitid: rptunitid
                  }
              })
              .then(res => {
                  this.InstrumentList = res.data1;
                  this.ResultList = res.data2;
                  this.resultnum = res.data2[0].value;
              })
              .catch(e => {});
      },
      OpenRptitem() {
          this.diagx = true;
          this.outerVisible = true;
      },
      addrptitem(c, n) {
          this.outerVisible = false;
          this.diagx = false;
          this.rpt_itemcode = c;
          this.rpt_itemname = n;
          this.InitPageDate();
      },
      InitPageDate() {
          if (this.rpt_itemcode == "") {
              this.$message.warning("请选择调整项目！");
              return false;
          }
          this.loading = true;
          this.$tool
              .request({
                  url: "LIS/LIS3/LIS321",
                  method: "post",
                  data: {
                      action: "InitPageDate",
                      rptunitid: this.txtrptunit,
                      rpt_itemcode: this.rpt_itemcode,
                      sampledatetime: this.sampledatetime,
                      sampleno: this.sampleno,
                      resulttxt: this.resulttxt,
                      checked: this.checked,
                      resultnum: this.resultnum,
                      instrument: this.instrument
                  }
              })
              .then(res => {
                  this.tableData = res.Data;
                  this.showval();
                  this.loading = false;
                  this.okFirstLoading = true;
              })
              .catch(e => {
                  this.loading = false;
              });
      },
      InitOption() {
          this.$tool
              .request({
                  url: "LIS/LIS3/LIS321",
                  method: "post",
                  data: {
                      action: "initoption",
                      rptunitid: this.txtrptunit,
                  }
              })
              .then(res => {
                  this.Options = res.options;
              })
              .catch({});
      },
      showval() {
          this.datacnt = this.tableData.length;
          this.dataavg = XEUtils.mean(this.tableData, "result_str").toFixed(2);
      },
      btnJustify() {
          if (this.justifyfun != "") {
              this.$confirm("你是否确定要调整?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  focusCancelButton: true,
                  type: "warning"
              })
                  .then(() => {
                      this.tableData.forEach(item => {
                          item.justifyresult = eval(this.justifyfun.replace("R", Number(item.result_str))).toFixed(2);
                      });
                  })
                  .catch(() => {
                      this.$message({
                          type: "info",
                          message: "已取消调整"
                      });
                  });
          } else {
              this.$message.error("无效的调整公式！");
          }
      },
      saverecord() {
          if (!this.islogin) {
              //未登录过
              this.$rm_Login({
                  type: "用户登录验证",
                  btn: {
                      confirmBtnText: "确定",
                      cancelBtnText: "取消"
                  }
              })
                  .then(res => {
                      console.log(res);
                      if (res.flag == "1") {
                          //登录成功
                          this.userno = res.userid;
                          this.islogin = true;
                          this.confirmSaverecord();
                      }
                  })
                  .catch(e => {
                      console.log("error", e);
                  });
          } else {
              //登录过
              this.confirmSaverecord();
          }
      },
      confirmSaverecord() {
          //初始化保存提示值
          this.saveSuccessCount = 0;
          this.saveErrorCount = 0;
          this.saveRsColor == "blue";
          this.saveRsText = "";
          this.saveSingleRecord(0);
      },

      saveSingleRecord(rownum){
          if (rownum < this.datacnt ){
              let rowdata = this.tableData[rownum];
              try{
                  this.$tool
                  .request({
                      url: "LIS/LIS3/LIS321",
                      method: "post",
                      data: {
                          action: "saverecord",
                          rptunitid: this.txtrptunit,
                          rpt_itemcode: this.rpt_itemcode,
                          sampledatetime: this.sampledatetime,
                          userno: this.userno,
                          saveinfo: rowdata
                      }
                  })
                  .then(res => {
                      rowdata.exeresult = res.exeresult;
                      if(res.returnflag == "1"){
                          this.saveSuccessCount ++;
                      }else{
                          this.saveErrorCount ++ ;
                          if (this.saveRsColor == "blue"){
                              this.saveRsColor = "red";
                          }
                      }
                      this.saveRsText = "保存提示：修改结果成功"+this.saveSuccessCount+"/"+this.datacnt+"条，失败"+this.saveErrorCount+"条！"
                      rownum ++ ;
                      this.saveSingleRecord(rownum);
                  });
              }catch (e) {
                      console.log("error", e);
              };
          }
      },

      btnRead() {
          this.InitPageDate();
      },
      btnDel() {
          if (!this.islogin) {
              //未登录过
              this.$rm_Login({
                  type: "用户登录验证",
                  btn: {
                      confirmBtnText: "确定",
                      cancelBtnText: "取消"
                  }
              })
                  .then(res => {
                      console.log(res);
                      if (res.flag == "1") {
                          //登录成功
                          this.userno = res.userid;
                          this.islogin = true;
                          this.confimdeleterecord();
                      }
                  })
                  .catch(e => {
                      console.log("error", e);
                  });
          } else {
              //登录过
              this.confimdeleterecord();
          }
      },
      confimdeleterecord() {
          //单条删除
          var delrow = this.$refs.xTable.getCurrentRow();
          if (delrow) {
              let message = "标本号：" + delrow.sampleno + "的结果是" + delrow.result_str + "，你确定要删除吗？";
              this.$confirm(message, "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  focusCancelButton: true,
                  type: "warning"
              })
                  .then(() => {
                      this.$tool
                          .request({
                              url: "LIS/LIS3/LIS321",
                              method: "post",
                              data: {
                                  action: "deleterecord",
                                  rptunitid: this.txtrptunit,
                                  rpt_itemcode: this.rpt_itemcode,
                                  sampledatetime: this.sampledatetime,
                                  sampleno: delrow.sampleno,
                                  userno: this.userno
                              }
                          })
                          .then(res => {
                              console.log(res);
                              if (res.flag == "1") {
                                  var alld = this.$refs.xTable.tableData;
                                  var rowindex = alld.indexOf(delrow);
                                  this.$refs.xTable.remove(delrow);
                                  this.tableData.splice(rowindex, 1);
                                  let havedata = this.$refs.xTable.tableData;
                                  if (havedata.length > 0) {
                                      if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                                      let selectrow = havedata[rowindex];
                                      this.$refs.xTable.setCurrentRow(selectrow);
                                  }
                                  this.showval();
                              } else {
                                  this.$message.error(res.msg);
                              }
                          })
                          .catch(e => {
                              console.log("error", e);
                          });
                  })
                  .catch(() => {
                      this.$message({
                          type: "info",
                          message: "已取消删除"
                      });
                  });
          }
      },
      btnDelAll() {
          if (!this.islogin) {
              //未登录过
              this.$rm_Login({
                  type: "用户登录验证",
                  btn: {
                      confirmBtnText: "确定",
                      cancelBtnText: "取消"
                  }
              })
                  .then(res => {
                      console.log(res);
                      if (res.flag == "1") {
                          //登录成功
                          this.userno = res.userid;
                          this.islogin = true;
                          this.confirmdeleteall();
                      }
                  })
                  .catch(e => {
                      console.log("error", e);
                  });
          } else {
              //登录过
              this.confirmdeleteall();
          }
      },
      confirmdeleteall() {
          this.$confirm("此操作将删除所有记录, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              focusCancelButton: true,
              type: "warning"
          })
              .then(() => {
                  this.$tool
                      .request({
                          url: "LIS/LIS3/LIS321",
                          method: "post",
                          data: {
                              action: "deleteall",
                              rptunitid: this.txtrptunit,
                              rpt_itemcode: this.rpt_itemcode,
                              sampledatetime: this.sampledatetime,
                              userno: this.userno,
                              saveinfo: this.$refs.xTable.tableData
                          }
                      })
                      .then(res => {
                          console.log(res);
                          res.forEach(item => {
                              if (item.exeresult == "OK") {
                                  this.tableData.forEach((element, rowindex) => {
                                      if (element.sampleno == item.sampleno) {
                                          this.$refs.xTable.remove(element);
                                          this.tableData.splice(rowindex, 1);
                                          this.showval();
                                      }
                                  });
                              } else {
                                  try {
                                      this.tableData.forEach(element => {
                                          if (element.sampleno == item.sampleno) {
                                              element.exeresult = item.exeresult;
                                              throw Error();
                                          }
                                      });
                                  } catch (e) {}
                              }
                          });
                      })
                      .catch(e => {
                          console.log("error", e);
                      });
              })
              .catch(() => {
                  this.$message({
                      type: "info",
                      message: "已取消删除"
                  });
              });
      },
      currentChangeEvent({ row }) {},
      opendialog({ row, column }) {
          if (column.property == "justifyresult") {
              this.outerVisible2 = true;
              this.selectrow = row;
          }
      },
      itemtxtresChage(val) {
          this.selectrow.justifyresult = val;
          this.outerVisible2 = false;
      },
      cellClassName() {},
      inputautofocus(evt, element) {
          if (element == "popinput1") {
              this.$refs.popinput1.blur();
              this.$refs.popinput2.$refs.ddlrptitemSelect.focus();
          } else if (element == "popinput2") {
              this.$refs.popinput3.focus();
          } else if (element == "popinput3") {
              this.InitPageDate();
              this.$refs.popinput4.focus();
          } else {
              this.btnJustify();
          }
      },
      ResultClass(row) {
          var stylestr = "padding:0 3px;";
          if (this.Options.resultcolor_mode == "1") stylestr += "color:";
          else stylestr += "background-color:";

          var flag = row.result_flag;
          switch (flag) {
              case "M":
                  stylestr += this.Options.resultcolor_m;
                  break;
              case "H":
                  stylestr += this.Options.resultcolor_h;
                  break;
              case "L":
                  stylestr += this.Options.resultcolor_l;
                  break;
              case "P":
                  stylestr += this.Options.resultcolor_p;
                  break;
              case "W":
                  stylestr += this.Options.resultcolor_w;
                  break;
              case "E":
                  stylestr += this.Options.resultcolor_e;
                  break;
              case "Q":
                  stylestr += this.Options.resultcolor_w;
                  break;
              default:
                  stylestr += this.Options.resultcolor_m;
                  break;
          }
          
          if (row.result_str == "未做") {
              stylestr += ";color: #0095D9";
          }
          return stylestr;
      },
      inputMove(type, column, rowIndex) {
          if (type == 1) {//下一个
              let row = this.$refs.xTable.tableData[rowIndex + 1];
              if (row) {
                  this.$refs.xTable.setCurrentRow(row);
                  this.$refs.xTable.setActiveCell(row, column.property);
              }
          } else {//上一个
              let row = this.$refs.xTable.tableData[rowIndex - 1];
              if (row) {
                  this.$refs.xTable.setCurrentRow(row);
                  this.$refs.xTable.setActiveCell(row, column.property);
              }
          }
      },
      enterMethod(column, rowIndex) {
          try {
              let thisrow = this.$refs.xTable.getCurrentRow();
              this.$tool
                  .request({
                      url: "ucent/ddl",
                      method: "post",
                      data: {
                          action: "ItemTxtResult",
                          rpt_itemcode: this.rpt_itemcode,
                          resultkind: "0",
                      },
                  })
                  .then((res) => {
                      var rdata = res.Data;
                      let tresult = rdata.filter((item) => item.inputcode == thisrow.justifyresult);
                      if (tresult != null && tresult.length > 0 && tresult[0].textvalue != "") {
                          thisrow.justifyresult = tresult[0].textvalue;
                      }
                      let neXTrow = this.$refs.xTable.tableData[rowIndex + 1];
                      this.$refs.xTable.setCurrentRow(neXTrow);
                      this.$refs.xTable.setActiveCell(neXTrow, "justifyresult");
                  })
                  .catch((e) => {
                      this.loading = false;
                  });
          } catch (e) {
              conso.log("error", e);
          }
      }
  }
};
</script>

<style scoped>
.pagetop {
  width: 100%;
  height: 130px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
  z-index: 99;
}

.pagecenter {
  position: absolute;
  top: 135px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}

.middle-center {
  position: absolute;
  height: 100%;
  left: 0px;
  right: 0px;
  overflow: auto;
}

.middle-right {
  position: absolute;
  height: 100%;
  width: 145px;
  right: 0px;
  border: 1px solid #ccc;
  padding: 6px;
}
.table1style tr td {
  padding: 0px 2px 0px 5px;
}

.table2style tr td {
  padding: 3px 2px 3px 5px;
}
</style>
